<template>
    <div>
        <h1>PLUM Canvas</h1>
        <canvas ref="plumCanvas" width="800" height="600"></canvas>
        <div>
            <div class="data-input">
                MAX_DEPTH: <input type="number" v-model="MAX_DEPTH">
                THRESHOLD: <input type="number" v-model="THRESHOLD">
                GAPTIME: <input type="number" v-model="GAPTIME">
                <button @click="treeint">REDRAW</button>
            </div>
        </div>
    </div>
</template>
<script>

export default {
    data(){
        return{
            canvas:null,
            ctx: null,
            LOWER_LENGTH: 8,
            UPPER_LENGTH: 20,
            LOWER_ANGLE: -160,
            UPPER_ANGLE: 160,
            GAPTIME: 150,
            MAX_DEPTH: 20,
            THRESHOLD: 2
        };
    },
    mounted() {
        this.canvas = this.$refs.plumCanvas;
        this.ctx = this.canvas.getContext('2d');
        this.treeint();
    },
    methods: {
        treeint() {
            this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
            try {
                this.drawTree(this.ctx, this.canvas.width / 2, this.canvas.height, -90, 100, this.MAX_DEPTH);
            } catch (error) {
                console.error('绘制树时发生错误:', error);
            }
        },  
        getRandomLength() {
            return Math.random() * (this.UPPER_LENGTH - this.LOWER_LENGTH) + this.LOWER_LENGTH;
        },
        getRandomAngle() {
            return Math.random() * (this.UPPER_ANGLE - this.LOWER_ANGLE) + this.LOWER_ANGLE;
        },
        drawTree(ctx, x, y, angle, length, depth) {
            if (depth <= 0) return;

            const newX = x + length * Math.cos(angle * Math.PI / 180);
            const newY = y + length * Math.sin(angle * Math.PI / 180);

            ctx.beginPath();
            ctx.moveTo(x, y);
            ctx.lineTo(newX, newY);
            ctx.stroke();

            const LEFT_ANGLE = angle - 10;
            const RIGHT_ANGLE = angle + 10;
            const LEFT_LENGTH = this.getRandomLength();
            const RIGHT_LENGTH = this.getRandomLength();

            const canDrawLeft = Math.random() * depth > this.THRESHOLD;
            const canDrawRight = Math.random() * depth > this.THRESHOLD;

            if (canDrawLeft) {
                setTimeout(() => {
                    this.drawTree(ctx, newX, newY, LEFT_ANGLE, LEFT_LENGTH, depth - 1);
                }, this.GAPTIME);
            }
            if (canDrawRight) {
                setTimeout(() => {
                    this.drawTree(ctx, newX, newY, RIGHT_ANGLE, RIGHT_LENGTH, depth - 1);
                }, this.GAPTIME);
            }
        }
    }
}
</script>


<style>
canvas {
    border: 1px solid black;
}
button {
    margin: auto;
}
</style>
